package com.droidbank;

import java.util.ArrayList;

import com.droidbank.model.Account;
import com.droidbank.model.DataModel;
import com.droidbank.util.DateComparison;
import com.droidbank.util.FormatDecimal;
import com.droidbank.util.UIUtil;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class AccountsActivity extends ListActivity {

	private TextView allMoney;
	private ProgressDialog progressDialog;
	private AccountAdapter accountAdapter;
	private DataModel dm;
	
	//---------------------- menu
	
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.options_menu, menu);
	    return true;
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.saveAction:
	    	UIUtil.showActivitySaveLoad(this, dm, "saveXML", true, false);
	        return true;
	    case R.id.settingsAction:
	    	startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
	        return true; 
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	
	//----------------------------------------------------------
	
	protected void onResume() {
		super.onResume();
		
		if(DataModel.isDirty)
			updateData(false); //just update data
		
		Log.d("DEBUG", "AccountsOnResume()");
	}
	
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_layout);
        
        dm = (DataModel)this.getApplication();
        
        //set reference
        if(DateComparison.dm ==null)
        	DateComparison.dm = dm;
        
        allMoney = (TextView) findViewById(R.id.allMoney);
        
        Log.d("DEBUG", "AccountsOnCreate()");
        
    	accountAdapter = new AccountAdapter(this, R.layout.account_row, dm.getAccountsAL());
		setListAdapter(accountAdapter);
	
		if(!DataModel.isDataLoaded){
		progressDialog = ProgressDialog.show(AccountsActivity.this,    
	              "Please wait...", "Processing data ...", true);
		
		//handle the work off the ui thread
		Runnable   viewOrders = new Runnable(){
			public void run() {
	                dm.load();
	                
	                runOnUiThread(new Runnable()
	                {
						public void run() {
						
							updateData(true);
			            	progressDialog.dismiss();
							
						}
	                	
	                });
	            }
		};
		
		
		new Thread(null, viewOrders, "loadXML").start();
		}
		else
			updateData(false); //just update data
	}

	
	private void updateData(boolean addAccounts)
	{
		double net =0;
		
		for(int i=0;i<dm.getAccountsAL().size();i++){
			
			if(addAccounts)
				accountAdapter.add(dm.getAccountsAL().get(i));
            net += (dm.getAccountsAL().get(i).getAmount() + dm.getAccountsAL().get(i).getStartingAmount());
		}
		
		String nets = new Double(FormatDecimal.format( 2, net)).toString();
		
    	accountAdapter.notifyDataSetChanged();
    	
    	allMoney.setText("Total: " + nets);
    	
    	DataModel.isDirty = false;
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		super.onListItemClick(l, v, position, id);

		Intent intent = new Intent(getApplicationContext(), ExpenseActivity.class);
		
		//pass account info to expenseList
		Bundle b = new Bundle();
		b.putInt(DataModel.ACCOUNT_INDEX, position);
		intent.putExtras(b);
	
		startActivity(intent);
		//finish();
	}
	
	private class AccountAdapter extends ArrayAdapter<Account> {

        private ArrayList<Account> items;

        public AccountAdapter(Context context, int textViewResourceId, ArrayList<Account> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.account_row, null);
                }
                Account o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        if (tt != null) {
                              tt.setText(o.getName());  
                              tt.setTextColor(0xffffffff);
                        }
                        if(bt != null){
                        	
                        	double val = o.getAmount() + o.getStartingAmount();
                        	if(val < 0)
                        		//red
                        		bt.setTextColor(0xFFCD0000);
                        	else
                        		//lime green
                        		bt.setTextColor(0xFF4EEE94);
                        	
                        	bt.setText(String.valueOf(FormatDecimal.format(2,val)));
                        }
                }
                return v;
        }
}
	
}
